import urllib2, re, Image, shutil, stat, os, random
from urllib import FancyURLopener

border = 5
bigw = 1920
bigh = 1200

class AgentOpener(FancyURLopener):
	version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
	
agent_opener = AgentOpener()

def getImages(file):
	data = file.read()
	return re.findall('src="([^"]*?/([^"/]*?_m.jpg))"', data)


def downloadImages(images):
	for image_url, image_name in images:
		print " -", image_name,
		local_file_path = "images/"+image_name
		if os.path.exists(local_file_path) and os.stat(local_file_path)[stat.ST_SIZE] > 1024: 
			print "exist!"
			continue
		local_image = open(local_file_path, "wb", 10240)
		remote_image = agent_opener.open(image_url)
		shutil.copyfileobj(remote_image, local_image)
		print "OK!"


def h_sorter(a, b):
	return cmp(a["h"]+a["y"], b["h"]+b["y"]) 

def findpos(w):
	global imagedb
	imagedb.sort(h_sorter)
	index = 0
	for image in imagedb:
		if image["w"] <= w:
			break
		else:
			index += 1
	if index > len(image): return None
	return imagedb.pop(index)

def createBigimage(images):
	global imagedb
	random.shuffle(images)
	bigim = Image.new("RGB", (bigw, bigh))
	nextx = border
	imagedb = []
	for image_url, image_name in images:
		im = Image.open("images/"+image_name)
		w,h = im.size
		if (nextx+border > bigw): #if its reached the image border
			parent_image = findpos(w)
			if not parent_image: continue #not found smaller image
			x = parent_image["x"]
			y = parent_image["y"]+parent_image["h"]+border
			neww = parent_image["w"]
			h = int(float(neww)/w*h)
			w = neww
			im = im.resize((w, h), Image.ANTIALIAS)
		else: #not reached the image border yet
			x = nextx
			y = border
			w = int(float(w)*0.7)
			h = int(float(h)*0.7)
			im = im.resize((w, h), Image.ANTIALIAS)
			nextx += w+border
		bigim.paste(im, (x, y))
		imagedb.append({"x": x, "y": y, "w": w, "h": h})
	return bigim

def setWallpaper( bmp ):
	import win32api, win32con, win32gui
	k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
	win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "0")
	win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
	win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp, 1+2)

print " * Opening mainpage..."
images = getImages(urllib2.urlopen("http://ffffound.com"))

randompage = str(500+random.randint(0,100)*25)
randompage = str(25)
print " * Opening random page...", randompage
images.extend( getImages(urllib2.urlopen("http://ffffound.com/?offset="+randompage)) )

print " * Downloading images..."
downloadImages(images)

print " * Creating Bigimage..."
createBigimage(images).save("C:\\windows\\ffffound.bmp")
setWallpaper("C:\\windows\\ffffound.bmp")

print " * All done!"